﻿using KinonekoSoftware.CodariaDB.Documents.Personalities;

namespace KinonekoSoftware.Studio.Pages.Notions
{
    public sealed class SentenceAsInspirationGalleryViewModel : RepositoryGalleryItem
    {
        private readonly CompositeEngine     _engine_sentence;
        private readonly InstanceCacheEngine _engine_cache;
        private readonly List<Sentence>      _collection;

        private Sentence _current;
        private int      _version;
        private int      _index;

        public SentenceAsInspirationGalleryViewModel()
        {
            Platform.GetEngine<CompositeEngine, InstanceCacheEngine>(out _, out _engine_sentence, out _engine_cache);
            _collection = new List<Sentence>(32);
            _index      = 0;


            PreviousItemCommand = CreateCommand(PreviousItem);
            RandomItemCommand   = CreateCommand(RandomItem);
            NextItemCommand     = CreateCommand(NextItem);
        }

        protected override void OnStart()
        {
            _collection.AddMany(_engine_sentence.GetSentences(), true);
            _version = _engine_sentence.Version;
            Current  = _collection.FirstOrDefault();
            base.OnStart();
        }

        protected override void OnResume()
        {
            if (_version != _engine_sentence.Version)
            {
                _collection.AddMany(_engine_sentence.GetSentences(), true);
                _version = _engine_sentence.Version;
                Current  = _collection.FirstOrDefault();
            }

            base.OnResume();
        }

        private void PreviousItem()
        {
            if (_collection.Count <= 0)
            {
                return;
            }

            _index  = (_index - 1) % _collection.Count;
            Current = _collection[_index];
        }

        private void RandomItem()
        {

            if (_collection.Count <= 0)
            {
                return;
            }

            _index  = Random.Shared.Next(0, _collection.Count - 1);
            Current = _collection[_index];

        }

        private void NextItem()
        {
            if (_collection.Count <= 0)
            {
                return;
            }

            _index  = (_index + 1) % _collection.Count;
            Current = _collection[_index];
        }


        public ICommandEX PreviousItemCommand { get; }
        public ICommandEX RandomItemCommand   { get; }
        public ICommandEX NextItemCommand     { get; }

        public InstanceCache CurrentCharacter { get; private set; }

        public Sentence Current
        {
            get => _current;
            set
            {
                SetValue(ref _current, value);

                if (_current is not null)
                {
                    CurrentCharacter = _engine_cache.Get(_current.From);
                    RaiseUpdated(nameof(CurrentCharacter));
                }
            }
        }
    }
}